package com.dongzili.easysearch.custom.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dongzili.easysearch.common.es.EsUtils;
import com.dongzili.easysearch.common.mybatisplus.MybatisPlusUtil;
import com.dongzili.easysearch.common.vo.R;
import com.dongzili.easysearch.custom.entity.SiExercise;
import com.dongzili.easysearch.custom.mapper.SiExerciseMapper;
import org.dromara.easyes.core.biz.EsPageInfo;
import org.dromara.easyes.core.conditions.select.LambdaEsQueryWrapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@RestController
public class SiExerciseController {

    @Resource
    SiExerciseMapper siExerciseMapper;

    @GetMapping("/getExercise")
    public R<?> getExercise(@RequestParam("keyword") String keyword){
        LambdaQueryWrapper<SiExercise> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(SiExercise::getIssue, keyword);
        wrapper.or().like(SiExercise::getAnalysis, keyword);

        IPage<SiExercise> pages = MybatisPlusUtil.getMapper(SiExercise.class).selectPage(new Page<>(1, 10), wrapper);
//        System.out.println(JSONUtil.toJsonStr(pages));
        return R.success(pages);
    }

    @GetMapping("/groupBy")
    public R<?> groupBy(){
        QueryWrapper<SiExercise> wrapper = new QueryWrapper<>();
        wrapper.lambda().like(SiExercise::getIssue, "医学");
        wrapper.lambda().groupBy(SiExercise::getSubType);
        wrapper.select("subType, count(*) as count");
        wrapper.orderByDesc("count");
        List<Map<String,Object>> mapList = siExerciseMapper.selectMaps(wrapper);

        System.out.println(JSONUtil.toJsonStr(mapList));
        return R.success(mapList);
    }

    @GetMapping("/es/getExercise")
    public R<?> getEsExercise(@RequestParam("keyword") String keyword){
        LambdaEsQueryWrapper<SiExercise> wrapper = new LambdaEsQueryWrapper<>();
        wrapper.like(SiExercise::getIssue, keyword);
        wrapper.or().match(SiExercise::getAnalysis, keyword);
        EsPageInfo<SiExercise> pages = EsUtils.getMapper(SiExercise.class).pageQuery(wrapper, 1, 10);
//        System.out.println(JSONUtil.toJsonStr(pages));
        return R.success(pages);
    }

}
